package cn.migu.music.hangupsms.dbcache;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.migu.music.hangupsms.common.config.HangUpSmsConfig;
import cn.migu.music.hangupsms.common.entity.BlackUserInfo;
import cn.migu.music.hangupsms.repository.BlackUserInfoDbMapper;

/**
 * 黑名单查询
 **/

@Component
public class BlackUserInfoMapper {
    @Autowired
    private BlackUserCacheManager blackUserCacheManager;
    @Autowired
    private BlackUserInfoDbMapper blackUserInfoDbMapper;
    @Autowired
    private HangUpSmsConfig       hangUpSmsConfig;

    public List<BlackUserInfo> selectByPage(String phoneNumber, Integer size) {
        return blackUserInfoDbMapper.selectByAllByPhoneNumber(phoneNumber, size);
    }

    public int selectCount() {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            return (int) blackUserCacheManager.getCount();
        }
        return blackUserInfoDbMapper.selectCount();
    }

    public void save(BlackUserInfo info) {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            List<BlackUserInfo> blackList = new ArrayList<>(1);
            blackList.add(info);
            blackUserCacheManager.batchInsert(blackList);
            return;
        }
        blackUserInfoDbMapper.save(info);
    }

    public void deleteBlack(String phonenumber) {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            blackUserCacheManager.batchDelete(Collections.singletonList(phonenumber));
            return;
        }
        blackUserInfoDbMapper.deleteBlack(phonenumber);
    }

    public BlackUserInfo queryBlackUserInfo(String phonenumber) {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            return blackUserCacheManager.queryBlackUserInfo(phonenumber);
        }
        return blackUserInfoDbMapper.queryBlackUserInfo(phonenumber);
    }

    public List<BlackUserInfo> queryBlackUserInfoList(List<String> phoneList) {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            return blackUserCacheManager.queryBlackUserInfoList(phoneList);
        }
        return blackUserInfoDbMapper.queryBlackUserInfoList(phoneList);
    }

    public void batchInsert(List<BlackUserInfo> userList) {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            blackUserCacheManager.batchInsert(userList);
            return;
        }
        blackUserInfoDbMapper.batchInsert(userList);
    }

    public int batchDelete(List<String> userList) {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            return blackUserCacheManager.batchDelete(userList);
        }
        return blackUserInfoDbMapper.batchDelete(userList);
    }
}
